<template>
    <el-form :inline="true">
        <el-form-item>
            <el-input v-model="searchForm.username" placeholder="员工名称" prefix-icon="el-icon-search"
                      clearable></el-input>
        </el-form-item>
        <el-form-item>
            <el-input v-model="searchForm.departmentName" placeholder="部门名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
            <el-button @click="getUserList()">搜索</el-button>
        </el-form-item>
        <el-form-item v-if="hasAuth('sys:user:save')">
            <el-button @click="dialogVisible = true" type="primary">新增</el-button>
        </el-form-item>
        <el-form-item v-if="hasAuth('sys:user:delete')">
            <el-popconfirm title="这是确定批量删除吗？" @confirm="delHandle(null)">
                <template #reference>
                    <el-button type="danger" slot="reference" :disabled="delBtlStatu">批量删除</el-button>
                </template>
            </el-popconfirm>
        </el-form-item>
        <el-form-item style="float: right">
            <!--&lt;!&ndash;            on-remove 文件列表移除文件时的钩子&ndash;&gt;
            &lt;!&ndash;            on-success文件上传成功时的钩子&ndash;&gt;
            &lt;!&ndash;            on-error	文件上传失败时的钩子&ndash;&gt;
            &lt;!&ndash;            action 上传的地址&ndash;&gt;
            &lt;!&ndash;            name 上传的文件字段名&ndash;&gt;
            &lt;!&ndash;            show-file-list	是否显示已上传文件列表&ndash;&gt;
            &lt;!&ndash;            on-preview	点击文件列表中已上传的文件时的钩子&ndash;&gt;
            <el-upload class="upload-demo"
                       ref="upload"
                       :action= this.fileUrl
                       name="excel"
                       :on-preview="handlePreview"
                       :on-remove="handleRemove"
                       :limit="1"
                       :on-exceed="handleExceed"
                       :before-upload="beforeAvatarUpload"
                       :on-change="handleChange"
                       :file-list="fileList"
                       accept=".xlsx,xls"
                       :auto-upload="false">
                <el-button slot="trigger" size="small" type="primary" @click="selectfile">选取文件</el-button>
                <div slot="tip" class="el-upload__tip">只能上传xlsx,xls文件</div>
            </el-upload>
            <el-button style="margin-left: 10px;" size="small" type="success" @click.native.prevent="submitUpload">点击上传</el-button>-->
            <el-upload
                    ref="upload"
                    class="upload-demo"
                    accept=".xlsx,.xls"
                    :auto-upload="false"
                    action=""
                    :limit="1"
                    :on-exceed="handleExceed"
                    :http-request="httpRequest"
            >
                <template #trigger>
                    <el-tooltip content="仅限文件格式为.xls、.xlsx" placement="top" effect="light">

                        <el-button type="primary">选择文件</el-button>
                    </el-tooltip>
                </template>
                <el-button
                        style="margin-left: 10px"
                        type="success"
                        @click="submitUpload"
                >立即导入<i class="el-icon-upload el-icon-right"></i>
                </el-button
                >
            </el-upload>
        </el-form-item>
    </el-form>

    <el-table
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="light"
            style="width: 99%"
            sroll
            border
            stripe
            @row-click="toggleSelection"
            @selection-change="handleSelectionChange"
            v-loading="loading"
            element-loading-text="拼命加载中..."
            element-loading-background="rgba(255, 255, 255, 0.7)"
    >
        <!--这里是表格-->
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="userId" label="员工号" width="120" sortable></el-table-column>
        <el-table-column prop="userName" label="员工名称" width="120"></el-table-column>
        <el-table-column prop="gender" label="性别" width="120" sortable>
            <template #default="scope">
                <span v-if="scope.row.gender === 1">男</span>
                <span v-if="scope.row.gender === 2">女</span>
            </template>
        </el-table-column>
        <el-table-column prop="phoneNum" label="手机号码" width="120" sortable></el-table-column>
        <el-table-column prop="departmentRoles" label="部门岗位">
            <template #default="scope">
                <el-tag size="small" type="info" v-for="item in scope.row.departmentRoles">{{ item.department.name}}-{{
                    item.sysRole.name }}
                </el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="hiredate" label="入职日期" width="120" sortable></el-table-column>
        <!--这里是操作栏-->
        <el-table-column label="操作"
                         v-if="hasAuth('sys:perm:list') || hasAuth('sys:user:repass') || hasAuth('sys:user:update') || hasAuth('sys:user:delete')">
            <template #default="scope">
                <el-button @click.prevent="permEditHandle(scope.row)" type="text" v-if="hasAuth('sys:perm:list')">分管权限
                </el-button>
                <el-divider direction="vertical" v-if="hasAuth('sys:perm:list')"></el-divider>

                <el-button @click="repassHandle(scope.row.id, scope.row.userName)" type="text"
                           v-if="hasAuth('sys:user:repass')">重置密码
                </el-button>
                <el-divider direction="vertical" v-if="hasAuth('sys:user:repass')"></el-divider>

                <el-button @click="editHandle(scope.row)" type="text" v-if="hasAuth('sys:user:update')">编辑</el-button>
                <el-divider direction="vertical" v-if="hasAuth('sys:user:update')"></el-divider>

                <el-popconfirm title="确定要删除这条记录吗？" @confirm="delHandle(scope.row.id)" v-if="hasAuth('sys:user:delete')">
                    <template #reference>
                        <el-button type="text">删除</el-button>
                    </template>
                </el-popconfirm>
            </template>
        </el-table-column>
    </el-table>

    <!--新增、编辑对话框-->
    <el-dialog title="用户信息"
               v-model="dialogVisible"
               width="600px"
               @close="resetForm('editForm')">
        <el-form :model="editForm" ref="editForm" :rules="editFormRules" label-width="100px">
            <el-form-item label="用户名" prop="userName">
                <el-input v-model="editForm.userName" autocomplete="off"></el-input>
                <el-alert title="初始密码为888888" :closable="false" type="info" show-icon
                          style="line-height: 12px;"></el-alert>
            </el-form-item>
            <el-form-item label="性別" prop="gender">
                <el-radio-group v-model="editForm.gender">
                    <el-radio :label="1">男</el-radio>
                    <el-radio :label="2">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="手机号" prop="phoneNum">
                <el-input v-model="editForm.phoneNum" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="部門崗位" prop="cascadeSelection">
                <el-cascader
                        style="width: 100%;"
                        v-model="editForm.cascadeSelection"
                        placeholder="试试搜索：开发部"
                        :options="options"
                        :props="props"
                        filterable
                ></el-cascader>
            </el-form-item>
            <el-form-item label="入职日期">
                <el-date-picker
                        style="width: 100%;"
                        v-model="editForm.hiredate"
                        type="date"
                        placeholder="选择入职日期"
                        :disabled-date="disabledDate"
                        :shortcuts="shortcuts"
                >
                </el-date-picker>
            </el-form-item>
        </el-form>
        <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitEditForm('editForm')">确 定</el-button>
        </span>
        </template>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" v-model="permDialogFormVisible" width="600px" @closed="resetForm('permForm')">
        <el-form :model="permForm" ref="permForm">
            <!--展开全部，父子不关联，有父子展开一定的有key,props设置显示格式，label,children-->
            <el-tree
                    :data="permTreeData"
                    show-checkbox
                    node-key="id"
                    ref="permTree"
                    :check-strictly="true"
                    :default-expand-all=true
                    :expand-on-click-node="false"
                    :check-on-click-node="true"
                    :props="defaultProps">
            </el-tree>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitPermFormHandle('permForm')">确 定</el-button>
            </span>
        </template>
    </el-dialog>

    <!--分页组件-->
    <div style="float: right;margin-top: 22px;">
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="current"
                :page-sizes="[5, 10, 20, 30]"
                :page-size="size"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
        >
        </el-pagination>
    </div>
</template>

<script>
    export default {
        name: "user",
        data() {
            return {
                loading: true,
                tableData: [],

                // 模糊搜索员工名称用到
                searchForm: {},

                // 根据多选的数量，将其批量按钮可用/不可用进行变化
                multipleSelection: [],
                delBtlStatu: true,

                // 对员工信息进行添加，编辑用到的对话框和对应的v-model绑定的数据和表单验证规则
                dialogVisible: false,
                editForm: {},
                editFormRules: {
                    userName: [
                        {required: true, message: '请输入用户名称', trigger: 'blur'}
                    ],
                    gender: [
                        {required: true, message: '请选择性别', trigger: 'blur'}
                    ],
                    cascadeSelection: [
                        {required: true, message: '请选择部门岗位', trigger: 'blur'}
                    ],
                    phoneNum: {min: 11, max: 11, message: '手机号码输入有误', trigger: 'blur'},
                },

                // 树形组件，授权时用到的数据
                permDialogFormVisible: false,
                permTreeData: [],
                defaultProps: {
                    children: 'children',
                    label: 'name'
                },
                // 用于分配权限时，临时保存是对哪个员工进行操作
                permForm: {id: ''},

                // 分页用到的属性
                total: 0,
                current: 1,
                size: 10,

                // 级联选择器需要的数据和设置的对应参数
                options: [],
                props: {
                    value: 'id',
                    label: 'name',
                    children: 'children',
                    multiple: true
                },
                // 级联选择器选择后返回一个[]，里面每一位为每一列表的id，如开发部-后台管理人员，勾选后为这个值，[[1,3]]，回显同个道理
                cascadeSelection: [],

                // 日期組件的参数
                disabledDate(time) {
                    return time.getTime() > Date.now()
                },
                shortcuts: [
                    {
                        text: '昨天',
                        value: new Date(),
                    },
                    {
                        text: '今天',
                        value: () => {
                            const date = new Date()
                            date.setTime(date.getTime() - 3600 * 1000 * 24)
                            return date
                        },
                    },
                    {
                        text: '一周前',
                        value: () => {
                            const date = new Date()
                            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
                            return date
                        },
                    },
                ],
            }
        },

        // 函数
        methods: {
            toggleSelection(row) {
                this.$refs.multipleTable.toggleRowSelection(row);
            },

            // 加载按分页查询的用户信息
            getUserList() {
                this.$axios.get('/sys/user/list', {
                    params: {
                        username: this.searchForm.username,
                        departmentName: this.searchForm.departmentName,
                        current: this.current,
                        size: this.size
                    }
                }).then(res => {
                    this.tableData = res.data.data.records
                    this.current = res.data.data.current
                    this.size = res.data.data.size
                    this.total = res.data.data.total
                    this.loading = false
                })
                // 用于树形组件的数据渲染
                this.$axios.get("/sys/menu/list").then(res => {
                    this.permTreeData = res.data.data
                })
                // 用于级联选择器数据的加载渲染
                this.$axios.get("/department/listAll").then(res => {
                    this.options = res.data.data
                })
            },

            // 用于树形组件 权限的回显选择
            permEditHandle(rowItem) {
                this.permDialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs.permTree.setCheckedKeys(rowItem.menuIds)
                    this.permForm.id = rowItem.id
                })
            },
            submitPermFormHandle(formName) {
                var menuIds = this.$refs.permTree.getCheckedKeys()

                console.log(menuIds)

                this.$axios.post('/sys/user/perm/' + this.permForm.id, menuIds).then(res => {
                    this.$message({
                        showClose: true,
                        message: '恭喜你，操作成功',
                        type: 'success',
                        onClose: () => {
                            this.getUserList()
                        }
                    });
                    this.$store.commit("changeRouteStatus", false)
                    this.permDialogFormVisible = false
                })
            },

            // 重置密码
            repassHandle(id, userName) {
                this.$confirm('将重置用户【' + userName + '】的密码, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios.post("/sys/user/repass", id).then(res => {
                        this.$message({
                            showClose: true,
                            message: '恭喜你，操作成功',
                            type: 'success',
                            onClose: () => {
                            }
                        });
                    })
                })
            },

            //点击编辑的事件，用于数据回显
            editHandle(row) {
                this.dialogVisible = true
                this.$nextTick(() => {
                    console.log(row)
                    this.editForm = JSON.parse(JSON.stringify(row))
                    let selectArr = []
                    row.departmentRoles.forEach(r => {
                        selectArr.push([r.departmentId, r.roleId])
                    })
                    this.editForm.cascadeSelection = selectArr
                })
            },
            // 新增、编辑表单提交
            submitEditForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        // 将级联数组保存的级联对象中第一位部门id,第二位位岗位id,更新要提交的行对象的部门岗位id
                        let departmentRoleArr = []
                        this.editForm.cascadeSelection.forEach(item => {
                            departmentRoleArr.push({"departmentId": item[0], "roleId": item[1]})
                        })
                        // 应该有把自身对象转为另一种格式的方法，如map??, 不然这样将自身格式化，集合起来，再来保存有点呆
                        this.editForm.departmentRoles = departmentRoleArr
                        console.log(this.editForm)
                        this.$axios.post('/sys/user/' + (this.editForm.id ? 'update' : 'save'), this.editForm)
                            .then(res => {

                                this.$message({
                                    showClose: true,
                                    message: '恭喜你，操作成功',
                                    type: 'success',
                                    onClose: () => {
                                        this.getUserList()
                                    }
                                });
                                this.dialogVisible = false
                            })
                    } else {
                        console.log('error rule');
                        return false;
                    }
                })
            },

            // 触发事件为有复选框发生变化，会传递所有勾选的行数据对象数组
            handleSelectionChange(val) {
                this.multipleSelection = val;
                //设置批量删除的按钮的可用/不可用
                this.delBtlStatu = val.length == 0
            },
            //这里是删除功能
            delHandle(id) {
                var ids = []
                if (id) {
                    ids.push(id)
                } else {
                    this.multipleSelection.forEach(row => {
                        ids.push(row.id)
                    })
                }
                this.$axios.post("/sys/user/delete", ids).then(res => {
                    this.$message({
                        showClose: true,
                        message: '恭喜你，操作成功',
                        type: 'success',
                        onClose: () => {
                            this.getUserList()
                        }
                    });
                })
            },

            // 新增、编辑对话框公用一个，新增不会回显，所以需要对其清空表单中的内容，以免切换(新增/编辑)后数据还在
            resetForm(formName) {
                this.$refs[formName].resetFields();
                this.dialogVisible = false
                this.editForm = {}
            },

            //这里是分页
            handleSizeChange(val) {
                this.size = val
                this.getUserList()
            },
            handleCurrentChange(val) {
                this.current = val
                this.getUserList()
            },


            //下面是批量导入用户所需的js
            handleExceed(files, fileList) {
                this.$message.warning('每次导入只能选择一个文件');
            },

            submitUpload() {
                this.$refs.upload.submit()
                /*
                // if(this.fileList.size < 0) {
                //     this.$message({
                //         showClose: true,
                //         message: '未选中文件',
                //         type: 'warning'
                //     })
                //     return false;
                // }

                }
                else {
                    console.log("是否进入")
                    let excel = new FormData();
                    excel.append("excel", this.file.raw);
                    this.$axios.post("/sys/user/import", excel,
                        {headers: {'Content-Type': 'multipart/form-data;boundary=OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp'}}
                    ).then(res => {
                        this.$message({
                            showClose: true,
                            message: '恭喜你,操作成功',
                            type: 'success'
                        });
                        this.$refs['upload'].clearFiles();
                        this.getUserList()
                        this.file=null;
                    }, error => {
                        this.$refs['upload'].clearFiles();
                        console.log(error)
                        this.file=null;
                    })
                }*/
            },

            //如果把提交函数用在http-request钩子中，fileList多长就执行请求多少次接口，依旧是无法做到只请求一次上传多文件
            httpRequest(param) {
                let excelFileObj = param.file
                let form = new FormData()// FormData 对象
                form.set('excel', excelFileObj)// 文件对象

                this.$axios.post("/sys/user/import", form, {headers: {'Content-type': 'multipart/form-data'}}).then(res => {
                    this.$message({
                        showClose: true,
                        message: '恭喜你，操作成功',
                        type: 'success',
                    });
                    this.getUserList()
                    this.$refs['upload'].clearFiles();
                })
            },
        },

        created() {
            this.getUserList()
        },
    }
</script>
<style scope>
    .el-tag {
        margin-right: 5px;
    }
</style>